package com.cqs.example.websocket.h5;

import lombok.extern.slf4j.Slf4j;
import org.springframework.http.server.ServerHttpRequest;
import org.springframework.http.server.ServerHttpResponse;
import org.springframework.http.server.ServletServerHttpRequest;
import org.springframework.web.socket.WebSocketHandler;
import org.springframework.web.socket.server.HandshakeInterceptor;

import java.net.URI;
import java.util.Map;

/**
 * @author lixiaowen
 * @date 2020/07/09
 */
@Slf4j
public class WebSocketInterceptor implements HandshakeInterceptor {

    public static final String WEB_SOCKET_CLIENT_ID = "WEB_SOCKET_CLIENT_ID";

    @Override
    public boolean beforeHandshake(ServerHttpRequest request, ServerHttpResponse serverHttpResponse, WebSocketHandler webSocketHandler, Map<String, Object> map) throws Exception {
        if (request instanceof ServletServerHttpRequest) {
            String clientId = getClientId(request.getURI());
            log.info("clientId:{} beforeHandshake", clientId);
            map.put(WEB_SOCKET_CLIENT_ID, clientId);
        }
        return true;
    }



    @Override
    public void afterHandshake(ServerHttpRequest serverHttpRequest, ServerHttpResponse serverHttpResponse, WebSocketHandler webSocketHandler, Exception e) {
        log.info("进来webSocket的afterHandshake拦截器！");
    }

    public static String getClientId(URI uri){
        String uri0 = uri.toString();
        int idx = uri0.lastIndexOf("/");
        //socket 用户标志
        String clientId = uri0.substring(idx + 1);
        return clientId;
    }
}